import React, {useEffect, useState} from "react";
import {useSelector,useDispatch} from "react-redux";
import {useParams} from "react-router-dom";
import './style.less'
import * as searchAction from "../../redux/actions/search"
import { useNavigate } from 'react-router-dom'
import {updateSearch} from "../../redux/actions/search";


//首页的搜索输入框以及搜索页面的搜索输入框公用组件
const SearchInput=(props)=>{
    /*const navigate = useNavigate()
    navigate('/test') // 跳转到/test
    navigate(-1) // 返回上一级
    navigate(0, {replace: true})// 强制刷新当前页面并不加入路由历史*/

    //为了让非路由组件也可以进行跳转
    const navigate=useNavigate()
    const[keywords,setkeywords]=useState("")
    const dispatch=useDispatch()
    const params=useParams()
    const reduxKeyWords=useSelector(state => state.search)


   //键盘移出事件调用函数
    function keyUpHandle(e){
        // console.log(e)
        // console.log(e.keyCode)
        // props.history.push("/") react-router-dom V5B版本中使用
        //react-router-dom中使用navigate

        if (keywords.length>0){
            if (e.keyCode===13){
                navigate("/search/"+keywords)

                //把关键词传给redux
                dispatch(searchAction.updateSearch(keywords))
                console.log("传到redux的"+keywords)


            }
        }
    }

    //回传关键词----这段代码在写的时候有点稀里糊涂
    useEffect(()=>{
        // console.log(params.keywords)
        if (params.keywords){
            dispatch(searchAction.updateSearch(params.keywords))
            console.log("执行了APP..........")
        }else {
            dispatch(searchAction.updateSearch(""))
        }
        setkeywords(reduxKeyWords.search)
    },[reduxKeyWords.search,params.keywords])

    //e.target.value是获取输入框中的值
    function changeHandle(e){
        setkeywords(e.target.value)
    }
    return (
        <input
            className="search-input"
            type="text"
            onKeyUp={keyUpHandle}
            value={keywords}
            onChange={changeHandle}
        />

    )
}
export default SearchInput